using System;
using System.Data;

namespace Developex.DatabaseWrapper.CSVImportExport
{
	///<summary>
	///</summary>
	public static class EIUtils
	{
		/// <summary>
		/// 
		/// </summary>
		public static string DateTimeFormat = "dd\\/MM\\/yyyy THH:mm:ss";

		///<summary>
		///</summary>
		///<param name="value"></param>
		///<returns></returns>
		public static string ParseValue(string value)
		{
			if (value == null)
				return null;

			if (value.StartsWith("\"") && value.EndsWith("\""))
			{
				value = value.Substring(1, value.Length - 2).Replace("\"\"", "\"");
			}

			return value;
		}

		///<summary>
		///</summary>
		///<param name="field"></param>
		///<param name="value"></param>
		///<returns></returns>
		public static object GetConvertedValue(IField field, string value)
		{
			object val = value;
			if (field.GetDbType().HasValue)
			{
				if (field.GetDbType().Value == DbType.DateTime)
				{
					DateTime dt;
					if (DateTime.TryParse(value, out dt))
					{
						val = dt;
					}
					else
					{
						val = null;
					}
				}
			}
			return val;
		}

		///<summary>
		///</summary>
		///<param name="val"></param>
		///<returns></returns>
		public static string GetStringValue(object val)
		{
			if (val is DateTime)
			{
				val = ((DateTime)val).ToString(DateTimeFormat);
			}
			return val == null ? "" : val.ToString();
		}

		///<summary>
		///</summary>
		///<param name="field"></param>
		///<returns></returns>
		public static string GetStringValue(IField field)
		{
			object val = field.GetValue();
			return GetStringValue(val);
		}
	}

}